package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.hosp.repository.DepartmentRepository;
import com.atguigu.yygh.hosp.service.DepartmentService;
import com.atguigu.yygh.model.hosp.Department;
import com.atguigu.yygh.vo.hosp.DepartmentQueryVo;
import com.atguigu.yygh.vo.hosp.DepartmentVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author zhmwi
 * @Date 2021/7/8
 * @Dersciption
 */
@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentRepository departmentRepository;
    //上传科室
    @Override
    public void save(Map<String, Object> paramMap) {
        //将map转为json
        String departmentJsonStr = JSONObject.toJSONString(paramMap);
        //将json转为对象
        Department department = JSONObject.parseObject(departmentJsonStr,Department.class);
        //根据医院编码、科室编码查询科室信息
        Department targetDepartment = departmentRepository.getDepartmentByHoscodeAndDepcode(department.getHoscode(),department.getDepcode());
        //判断
        if (targetDepartment == null){
            //保存
            department.setCreateTime(new Date());
            department.setUpdateTime(new Date());
            department.setIsDeleted(0);
            departmentRepository.save(department);
        }else{
            //修改
            targetDepartment.setUpdateTime(new Date());
            targetDepartment.setIsDeleted(0);
            departmentRepository.save(targetDepartment);
        }
    }

    //分页查询科室
    @Override
    public Page<Department> queryByPage(Integer page, Integer limit, DepartmentQueryVo departmentQueryVo) {

        Department department = new Department();
        //将医院编号拷贝到科室
        BeanUtils.copyProperties(departmentQueryVo,department);
        department.setIsDeleted(0);

        //根据创建时间降序排序
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");

        //创建匹配器 即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)//改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true);//忽略大小写
        //0为第一页 降序排序
        PageRequest pageable = PageRequest.of(page - 1, limit, sort);
        Example<Department> example = Example.of(department, matcher);
        Page<Department> pages = departmentRepository.findAll(example, pageable);
        return pages;
    }

    //删除科室
    @Override
    public void remove(String hoscode, String depcode) {
        Department targetDepartment = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        if (targetDepartment != null){
            departmentRepository.deleteById(targetDepartment.getId());
        }

    }

    //根据医院code查询所有科室
    @Override
    public List<DepartmentVo> getDepartmentList(String hoscode) {
        //创建最终返回对象
        ArrayList<DepartmentVo> result = new ArrayList<>();

        //根据医院编号，查询医院所有科室信息
        Department departmentQuery = new Department();
        departmentQuery.setHoscode(hoscode);
        Example example = Example.of(departmentQuery);
        //所有科室列表 departmentList
        List<Department> deptList = departmentRepository.findAll(example);

        //处理科室集合：根据大科室id进行划分，用流式计算
        //key: bigCode
        //value: 当前大科室下小科室集合 [{}.{}...]
        Map<String, List<Department>> departmentMap = deptList.stream()
                                                      .collect(Collectors.groupingBy(Department::getBigcode));
        //遍历
        for (Map.Entry<String, List<Department>> entry : departmentMap.entrySet()) {
            //封装大科室 key
            DepartmentVo bigDepartmentVo = new DepartmentVo();
            bigDepartmentVo.setDepcode(entry.getKey());
            bigDepartmentVo.setDepname(entry.getValue().get(0).getBigname());

            //封装小科室 value [{},{}...]
            List<Department> entryValue = entry.getValue();

            ArrayList<DepartmentVo> deptChild = new ArrayList<>();

            for (Department department : entryValue) {
                DepartmentVo departmentVo = new DepartmentVo();
                BeanUtils.copyProperties(department,departmentVo);
                deptChild.add(departmentVo);
            }
            //小科室集合存入大科室
            bigDepartmentVo.setChildren(deptChild);
            //大科室存入返回集合
            result.add(bigDepartmentVo);
        }

        return result;
    }

    //根据科室编号，和医院编号，查询科室名称
    @Override
    public String getDepName(String hoscode, String depcode) {
        Department department
                = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        if(department != null) {
            return department.getDepname();
        }
        return "";
    }

    @Override
    public Department getDepartment(String hoscode, String depcode) {
        Department department
                = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        return department;
    }
}
